<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>chunk编码传输</title>
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
</head>
<body>
<h1>{{$name}}</h1>
<div style="color: blue" id="content">返回内容: </div>
</body>
<script>

    function  xhrOnProgress(fun) {
        return function() {
            let xhr = $.ajaxSettings.xhr();
            if (typeof fun !== 'function')
                return xhr;
            if (fun) {
                xhr.addEventListener('progress', fun);
            }
            return xhr;
        }
    }


    let indexPos = 0;
    let chunkIndex = 1;

    $.ajax({
        type: "POST",
        url: "http://192.168.33.10:9301/chunk",
        data: {name: "test"},
        success: function(msg){
            // console.log(msg)
        },
        error: function(xhr, status, error) {
            console.log(error); // 处理请求失败的错误信息
        },
        xhr: xhrOnProgress(function(event) { // 每次读取chunk的进度数据
            const xhr = event.target
            const {responseText} = xhr

            /*let thunks = responseText.substring(chat.lastChunkIndex);
            chat.lastChunkIndex = responseText.length;
            const arr = thunks.split("\n");*/

            // chunks的数据
            let chunkResult = responseText.substring(indexPos);
            // indexPos重新赋值
            indexPos = responseText.length;

            // 通过截取的方式，获得数据每次chunk的数据
            console.log('第【' + chunkIndex + '】chunk的数据：')
            // console.log(responseText)
            console.log(chunkResult)

            let splitResult = chunkResult.split('\n');
            splitResult.forEach(function(chunk) {
                if (chunk) {
                    let obj = JSON.parse(chunk)
                    let content = obj.data.id;
                    $('#content').append(content + ' ')
                }

            })

            chunkIndex ++;


            // arr.forEach(function (chunk) {
            //     if (chunk === '') return;
            //     chunk = chunk.substring(6).trim();
            //     if (chunk === '' || chunk === '[DONE]') return;
            //     try {
            //         const data = JSON.parse(chunk);
            //         if (message.error) {
            //             message.choices[0].delta.content += message.error.message || '';
            //         } else {
            //             message.choices[0].delta.content += data.choices[0].delta.content || '';
            //         }
            //         app.scrollToBottom();
            //     } catch (e) {
            //
            //     }
            // });
        })
    });
</script>
</html>